package com.internet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 手写下载静态资源
 * 获取并下载Tomcat上的资源
 * 以下异常处理也推荐try-catch
 */
public class URLTest1 {

    public static void main(String[] args) throws IOException {

        URL url = new URL("http://localhost:8080/examples/hello.txt");

        //获取服务器的连接
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();

        FileOutputStream fileOutputStream = new FileOutputStream("hello1.txt");

        byte[] buffer = new byte[1024];

        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            fileOutputStream.write(buffer, 0, len);
        }

        //关闭资源
        inputStream.close();
        fileOutputStream.close();
        //断开连接
        urlConnection.disconnect();

    }
}
